<?php

namespace app\common\model;

use app\common\controller\Queue;
use think\Db;
use think\Model;


class UserSale extends Model
{

    

    

    // 表名
    protected $name = 'user_sale';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	/**
	 * 记录升级订单数量统计
	 * @param $userId
	 * @param $parents
	 * @param $number
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addNumber($userId, $parents, $number) {
		
		$selfRes = $this->changeNumber($userId, $number, 'self_number');
		if(!$selfRes) {
			$this->error = '添加自购数量出错';
			return false;
		}
		
		$task[] = [
			'method' => 'checkLevel',
			'data' => ['user_id' => $userId]
		];
		
		
		if($parents) {
			foreach ($parents as $item) {
				$teamRes = $this->changeNumber($item['user_id'], $number, 'team_number');
				if(!$teamRes) {
					$this->error = '添加上级'.$item['user_id'].'团队数量出错';
					return false;
				}
				$task[] = [
					'method' => 'checkLevel',
					'data' => ['user_id' => $item['user_id']]
				];
			}
		}
		
		return $task;
	}
	
	/**
	 * 添加数量
	 * @param $userId
	 * @param $number
	 * @param $field
	 * @return false|int|true
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function changeNumber($userId, $number, $field) {
		$row = $this->where(['user_id' => $userId])->find();
		if($row) {
			$res = $this->where(['id' => $row['id']])
				->setInc($field, $number);
		} else {
			$res = Db::name('userSale')
				->insert([
				'user_id' => $userId,
				$field => $number,
					'create_time' => time(),
					'update_time' => time(),
			]);
		}
		
		return $res;
	}

}
